package com.zhenyi.youqu.core;

import org.joda.time.DateTime;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.utils.AuthUtils;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqOrder;
import com.youqu.common.model.YqShop;
import com.youqu.common.model.YqUser;
import com.zhenyi.youqu.interceptor.MiniappAuthInterceptor;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;

@Before(MiniappAuthInterceptor.class)
public class YQMiniAppController extends YQController {

	/**
	 * 是否允许多次购买团购
	 */
	protected final boolean EN_MUTI_PAY_GROUP = PropKit.getBoolean("YQ_MUTI_PAY_GROUP", false);
	/**
	 * 是否允许直接支付未支付订单,直接查找未支付订单
	 */
	protected final boolean EN_REPAY_PRODUCT = PropKit.getBoolean("EN_REPAY_PRODUCT", false);

	/**
	 * 通过token,openid获取用户
	 * 
	 * @return
	 */
	protected YqUser getUser() {
		// return YqUser.dao.findById(17);
		String openId = getPara("openId");
		String token = getPara("token");
		if (StrKit.notBlank(openId)) {
			YqUser user = YqUser.dao.searchFirst("openId", openId);
			if (user != null) {
				return user;
			}
		}
		if (StrKit.notBlank(token)) {
			String uid = AuthUtils.getTokenUid(this);
			YqUser user = YqUser.dao.findById(uid);
			if (user != null) {
				return user;
			}
		}
		LogKit.error("can't get user");
		return null;
	}

	/**
	 * 通过商户号获得shopId
	 * 
	 * @return
	 * @Time 2019年3月4日 下午11:52:51
	 */
	protected Long getParaShopId() {
		String code = getPara("code");
		Long shopId = null;
		if (StrKit.isBlank(code)) {
			return null;
		}
		if (!NumberUtil.isNumber(code)) {
			return null;
		}
		try {
			shopId = HASHID.decode(code)[0];
		} catch (Exception e) {
			return null;
		}
		YqShop shop = YqShop.dao.findById(shopId);
		if (shop == null) {
			return null;
		}
		return shopId;
	}

	protected void renderPay(YqOrder order) {
		Long projectAppId = order.getProjectAppId();
		YqApp app = YqApp.dao.findByAppId(projectAppId);
		renderWechatPay(order.getPrepayId(), app.getWechatMiniAppId(), app.getWechatPartnerKey());
	}

	protected void renderWechatPay(String prepay_id, String appId, String partnerKey) {
		// String nonce_str = System.currentTimeMillis() / 1000 + "";
		String nonce_str = RandomUtil.randomString(32);

		DateTime dateTime = new DateTime();
		String timeStamp = dateTime.toDate().getTime() / 1000 + "";
		String signString = "appId=" + appId + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id
				+ "&signType=MD5&timeStamp=" + timeStamp + "&key=" + partnerKey;
		signString = HashKit.md5(signString).toUpperCase();
		DBMap map = new DBMap();
		map.put("sign", signString);
		map.put("timeStamp", timeStamp);
		map.put("nonce_str", nonce_str);
		map.put("package", prepay_id);
		map.put("prepay_id", prepay_id);
		map.put("signType", "MD5");
		renderResult(map, "pay", 200);
	}

}
